package scan

import (
	//"flag"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"runtime"
	"strconv"
	"time"
)

const (
	// 获取某书下的所有分卷信息
	GetVolumeByBookID = "http://lknovel.lightnovel.cn/apis/h5/GetVolumeByBookID/"
	// 章节内容
	GetContentByChapterID = "http://lknovel.lightnovel.cn/apis/h5/GetContentByChapterID/"

	TIME_OUT = "time out"
	SUCCEED  = "succeed"
	ERROR    = "error"
)

func Scan(from int, to int) {
	var c chan string
	c = make(chan string, to-from+1)
	runtime.GOMAXPROCS(16)
	for i := from; i <= to; i++ {
		time.Sleep(time.Millisecond * 300)
		//fmt.Println("Run: ", i)
		go Run(i, c)
	}
	for i := from; i <= to; i++ {
		// should use log
		<-c
	}
}

// 对ScanBook做的并发封装
func Run(bid int, c chan string) {
	conn, err := redis.Dial("tcp", ":6379")
	if err != nil {
		log.Fatal(err)
	}
	flag := false //信号灯
	id := strconv.Itoa(bid)
	// 超时机制
	go func(flag *bool) {
		// 是不是什么样的姿势都有啊
		time.Sleep(time.Second * 60)
		if *flag == false {
			*flag = true
			fmt.Println("TIMEOUT TIMEOUT TIMEOUT")
			c <- id + ":" + TIME_OUT
		}
	}(&flag)

	// get the body data
	res, err := http.Get(GetVolumeByBookID + id)
	defer res.Body.Close()
	if !flag && err != nil {
		flag = true
		fmt.Println(err)
		c <- id + ":" + ERROR
	}

	// oprate
	err = ScanBook(conn, id, res.Body)
	if !flag {
		flag = true
		if err != nil {
			fmt.Println(id, ":", err)
			c <- id + ":" + ERROR
		} else {
			c <- id + ":" + SUCCEED
		}
	}
	//fmt.Println(bid, ":完成")
}
